/*
 * @Author: zi.yang
 * @Date: 2022-02-03 00:19:41
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-02-10 22:33:03
 * @Description: app
 * @FilePath: \api-generator\app.js
 */
'use strict';

module.exports = app => {
  // 处理用户信息
  app.passport.verify(async (ctx, user) => {
    const loginInfo = await ctx.service.user.login(user);
    if (loginInfo.success) {
      // id存入Cookie, 用于验证过期.
      const auth_token = loginInfo.data._id + '$$$$';
      // cookie 不设置时间，即可关闭浏览器自动清除
      const opts = {
        path: '/',
        // maxAge: 1000 * 60 * 60,
        signed: true,
        httpOnly: true,
      };
      ctx.cookies.set(app.config.auth_cookie_name, auth_token, opts);
      return loginInfo.data;
    }
    return null;
  });
  // 序列化用户信息
  app.passport.serializeUser(async (ctx, user) => {
    if (!user) return null;
    return user;
  });
  // 反序列化用户信息
  app.passport.deserializeUser(async (ctx, user) => {
    if (!user) return null;
    const auth_token = ctx.cookies.get(ctx.app.config.auth_cookie_name, {
      signed: true,
    });

    if (!auth_token) return null;

    const auth = auth_token.split('$$$$');
    const user_id = auth[0];
    const userInfo = await ctx.service.user.getUserById(user_id);

    if (!userInfo.success) return null;
    return userInfo.data;
  });
};
